package oop.ex3.filemanager;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

import oop.ex3.messages.*;
import oop.ex3.sockets.ClientSocket;

public class UploadThread implements Runnable  {
	
	ClientSocket _socket;
	FMContext _context;
	
	public UploadThread(Socket s, FMContext context){
		try {
			_socket = new ClientSocket(s);
		} catch (IOException e) {
			
		}
		_context = context;
	}

	public void run() {
		try {
			MessageInterface msg = _socket.readMessage();
			//if it's not a wantFile message- ignore it
			if (msg.getHeader().equals(ValidHeaders.WANTFILE)){
				String file = ((FileMessage)msg).getFileName();
				FileInfo fileInfo;
				if ((fileInfo =_context.getFileInfo(file))!= null){
					fileInfo.addUpload();
					//TODO add to finally
					_socket.SendMessage(new FileContentMessage(
							ValidHeaders.FILE , new File(_context.getDir()
									+File.separator+file)));
					System.out.println("im in upload thread");
					fileInfo.substructUpload();
					synchronized(fileInfo){
						System.out.println("going to nogify");
						fileInfo.notifyAll();	
					}
				} else {
					//file not exist
					_socket.SendMessage(new 
							SimpleMessage(ValidHeaders.FILENOTFOUND));
				}
			}
			//TODO close socket, do i need to send done?
			_socket.closeClientSocket();
		} catch (Exception e) {
			//if FM can't read the message it simply doesnt reply
			e.printStackTrace();
		}
		
		
	}

}
